package com.wnhz.work.yz.activity;

import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.utils.AlbumImagePath;
import com.wnhz.work.yz.view.SkillBookPop;

import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ExErrActivity extends BaseActivity implements View.OnClickListener {
    private RecyclerView recycler;
    private String budget_id = "";

    private List<String> imgUrl = new ArrayList<>();
    private ImageView add_img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ex_err);
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("装车清单");
        budget_id = getIntent().getStringExtra("budget_id");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        TextView submit = (TextView) findViewById(R.id.submit);
        submit.setText("提交");
        submit.setVisibility(View.VISIBLE);
        submit.setOnClickListener(this);
        recycler = (RecyclerView) findViewById(R.id.recycler);
        recycler.setLayoutManager(new GridLayoutManager(this, 4, LinearLayoutManager.VERTICAL, false));
        myadapter2 = new Myadapter2(this, imgUrl);
        recycler.setAdapter(myadapter2);
        add_img = (ImageView) findViewById(R.id.add_img);
        add_img.setOnClickListener(this);
    }

    private Myadapter2 myadapter2;

    class Myadapter2 extends BaseRVAdapter {

        /**
         * 构造器
         *
         * @param context 上下文
         * @param list    数据集合
         */
        public Myadapter2(Context context, @NonNull List list) {
            super(context, list);
        }

        @Override
        public int getLayoutId(int viewType) {
            return R.layout.dialog_add_tupian;
        }

        @Override
        public void onBind(BaseViewHolder holder, final int position) {
            x.image().bind(holder.getImageView(R.id.add_tu), imgUrl.get(position));
            holder.getView(R.id.delete).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    imgUrl.remove(position);
                    Myadapter2.this.notifyDataSetChanged();
                    add_img.setVisibility(View.VISIBLE);
                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.submit:
                MyToast("提哦啊囧");
                break;
            case R.id.add_img:
                showPopmenu(v);
                break;
        }
    }

    private WindowManager.LayoutParams lp;
    private SkillBookPop menuWindow;
    private final int FROM_CAMERA_CODE = 111;// 调用相机更改背景图片的请求code
    private final int FROM_ALBUM_CODE = 112;// 调用相册更改背景图片的请求code

    public void showPopmenu(View v) {
        menuWindow = new SkillBookPop(this, menuItemsOnClick);
        menuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });

        menuWindow.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        lp = getWindow().getAttributes();
        // lp.alpha = 0.6f;
        getWindow().setAttributes(lp);

    }


    private String imageName = "";
    /**
     * 弹出pop的菜单点击事件
     */
    private View.OnClickListener menuItemsOnClick = new View.OnClickListener() {
        Intent intent = null;


        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.from_camera2:

                    intent = new Intent("android.media.action.IMAGE_CAPTURE");
                    // 判断存储卡是否可以用，可用进行存储
                    if (hasSdcard()) {
                        String time = System.currentTimeMillis() + "";
                        imageName = time + ".jpg";
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/youZhu/", imageName)));
                    }
                    startActivityForResult(intent, FROM_CAMERA_CODE);

                    break;
                case R.id.from_album2:
                    Intent intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, FROM_ALBUM_CODE);
                    break;

                default:
                    break;
            }
        }
    };

    public void showDialogv7(String title, DialogInterface.OnClickListener clickListener) {
        /***
         这里使用了 android.support.v7.app.AlertDialog.Builder
         可以直接在头部写 import android.support.v7.app.AlertDialog
         那么下面就可以写成 AlertDialog.Builder
         */
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setMessage(title);
        builder.setNegativeButton("取消", null);
        builder.setPositiveButton("确定", clickListener);
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            //相册
            case FROM_ALBUM_CODE:
                Bitmap bm = null;
                ContentResolver resolver = getContentResolver();

                if (null != data) {
                    Uri uri = data.getData();
                    String imagePath = AlbumImagePath.getPath(this, uri);
                    updateImage(imagePath, uri);

                }
                break;
            //拍照
            case FROM_CAMERA_CODE:
                boolean hasSdcard = hasSdcard();
                if (hasSdcard) {
                    File tempFile = new File(Environment.getExternalStorageDirectory() + "/youZhu/", imageName);
                    Uri uri = Uri.fromFile(tempFile);

                    String imagePath = tempFile.getAbsolutePath();
                    System.out.println("拍照的路径=====：" + imagePath);

                    File file = new File(imagePath);
                    if (!file.exists()) {
                        return;
                    }
                    updateImage(imagePath, uri);
                } else {
                    MyToast("未找到存储卡，无法存储照片！");
                }
                break;

        }
    }

    private void updateImage(String imagePath, Uri uri) {
        if (null == imagePath) {
            return;
        }


        if (imgUrl.size() < 4) {
            imgUrl.add(imagePath);
            myadapter2.notifyDataSetChanged();
        }
        if (imgUrl.size() >= 4) {
            add_img.setVisibility(View.GONE);
        } else {
            add_img.setVisibility(View.VISIBLE);
        }
        Log.e("img", imgUrl.size() + "");
    }

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
}
